package cn.dida.dao;

import java.util.HashMap;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import cn.dida.model.Department;

/**
 * 部门管理 数据交互类
 * @author weiwei
 */
@Repository
public class DepartmentDao extends DaoBase {

	/**
	 * 根据公司id获取部门列表
	 * @param companyId 公司id
	 * @return List<Department> 部门列表
	 */
    public List<Department> getAll(Integer companyId) {
        String sql = "select * from department where company_id = ?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Department.class), companyId);
    }

    /**
     * 新增部门
     * @param department 部门实体类
     * @return int 受影响的记录行数
     */
    public int insert(Department department) {
        String sql = "insert into department (id, parent_id, name, `order`, company_id) values(:id, :parent_id, :name, :order, :company_id)";
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", department.getId());
        paramMap.put("parent_id", department.getParentId());
        paramMap.put("name", department.getName());
        paramMap.put("order", department.getOrder());
        paramMap.put("company_id", department.getCompanyId());
        return namedParameterJdbcTemplate.update(sql, paramMap);
    }
    /**
     * 更新部门 
     * @param department 部门实体类
     * @return int 受影响的记录行数
     */
    public int update(Department department) {
        String sql = "update department set name=:name, `order`=:order, parent_id=:parent_id where company_id = :company_id and id = :id";
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", department.getId());
        paramMap.put("parent_id", department.getParentId());
        paramMap.put("name", department.getName());
        paramMap.put("order", department.getOrder());
        paramMap.put("company_id", department.getCompanyId());
        return namedParameterJdbcTemplate.update(sql, paramMap);
    }

    /**
     * 根据公司id和部门id获取部门信息
     * @param companyId	公司id
     * @param id 部门id
     * @return Department 部门信息
     */
    public Department get(Integer companyId, Integer id) {
        String sql = "select * from department where company_id = ? and id = ?";
        try {
            Department department = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Department.class), companyId, id);
            return department;
        } catch (DataAccessException e) {
            return null;
        }
    }

    /**
     * 删除部门
     * @param companyId 公司id
     * @param id 部门id
     * @return int 受影响的记录行数
     */
    public int delete(Integer companyId, Integer id) {
        String sql = "delete from department where company_id = ? and id = ?";
        return jdbcTemplate.update(sql, companyId, id);
    }
}
